package fr.istic.linkedcv.client.presentation.views.impl;

import java.util.HashMap;
import java.util.Map;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

import fr.istic.linkedcv.client.presentation.impl.UiImpl;
import fr.istic.linkedcv.client.presentation.views.View;
import fr.istic.linkedcv.client.services.PersonneService;
import fr.istic.linkedcv.client.services.PersonneServiceAsync;

public class GroupesForm extends View {

	private Grid grid = new Grid(2, 2);
	private Label nameLabel = new Label("Nom : ");
	private TextBox name = new TextBox();
	Button submitBtn = new Button("Enregistrer");
	private final PersonneServiceAsync personneService = GWT.create(PersonneService.class);
	protected boolean CvExist;

	public GroupesForm(UiImpl ui) {
		super(ui);
		
	}

	@Override
	public Widget getWidget() {
		// TODO Auto-generated method stub
		return grid;
	}

	public void build() {
		submitHandler();
		grid.setWidget(0, 0, nameLabel);		
		grid.setWidget(0, 1, name);
		grid.setWidget(1, 0, submitBtn);
		grid.setHeight("90px");
	}

	protected String setWidgetText(String text) {
		return (text!=null)?text:"";
		
	}

	private void submitHandler() {
		submitBtn.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				if (name.getValue().isEmpty()) {
					Window.alert("Le champ nom doit être saisi.");
				}else{
					createGroupe();
				}

			}

			private void createGroupe() {
				Map<String,String> groupe = new HashMap<String, String>();
				groupe.put("name", name.getValue());
				personneService.createGroupe(groupe, new AsyncCallback<Boolean>() {
					
					@Override
					public void onSuccess(Boolean result) {
						ui.addHistoryItem("my_groupes");
						
					}
					
					@Override
					public void onFailure(Throwable caught) {
						Window.alert("failure");
						
					}
				});
				
			}
		});

	}

	

}
